import React, { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { 
  Package, 
  Clock, 
  Truck, 
  CheckCircle, 
  XCircle,
  Eye,
  ShoppingBag
} from 'lucide-react';
import { orderApi } from '@/db/api';
import { useAuth } from 'miaoda-auth-react';
import type { Order } from '@/types/types';
import { toast } from 'sonner';

const Orders: React.FC = () => {
  const navigate = useNavigate();
  const { user } = useAuth();
  
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState('all');

  useEffect(() => {
    if (!user) {
      navigate('/login');
      return;
    }
    loadOrders();
  }, [user, navigate]);

  const loadOrders = async () => {
    try {
      setLoading(true);
      const data = await orderApi.getUserOrders();
      setOrders(data);
    } catch (error) {
      console.error('加载订单失败:', error);
      toast.error('加载订单失败');
    } finally {
      setLoading(false);
    }
  };

  const getStatusInfo = (status: Order['status']) => {
    switch (status) {
      case 'pending':
        return {
          label: '待付款',
          color: 'bg-yellow-100 text-yellow-800',
          icon: Clock
        };
      case 'paid':
        return {
          label: '已付款',
          color: 'bg-blue-100 text-blue-800',
          icon: Package
        };
      case 'shipped':
        return {
          label: '已发货',
          color: 'bg-purple-100 text-purple-800',
          icon: Truck
        };
      case 'delivered':
        return {
          label: '已完成',
          color: 'bg-green-100 text-green-800',
          icon: CheckCircle
        };
      case 'cancelled':
        return {
          label: '已取消',
          color: 'bg-red-100 text-red-800',
          icon: XCircle
        };
      default:
        return {
          label: '未知',
          color: 'bg-gray-100 text-gray-800',
          icon: Package
        };
    }
  };

  const getFilteredOrders = (status?: string) => {
    if (!status || status === 'all') return orders;
    return orders.filter(order => order.status === status);
  };

  const OrderCard = ({ order }: { order: Order }) => {
    const statusInfo = getStatusInfo(order.status);
    const StatusIcon = statusInfo.icon;

    return (
      <Card className="hover:shadow-lg transition-shadow duration-300">
        <CardHeader className="pb-4">
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="text-lg">订单号: {order.order_number}</CardTitle>
              <p className="text-sm text-gray-500 mt-1">
                下单时间: {new Date(order.created_at).toLocaleString()}
              </p>
            </div>
            <Badge className={statusInfo.color}>
              <StatusIcon className="h-4 w-4 mr-1" />
              {statusInfo.label}
            </Badge>
          </div>
        </CardHeader>
        
        <CardContent className="space-y-4">
          {/* Order Items */}
          <div className="space-y-3">
            {order.order_items?.slice(0, 3).map((item) => (
              <div key={item.id} className="flex items-center gap-3">
                <div className="w-16 h-16 flex-shrink-0 overflow-hidden rounded-lg">
                  <img
                    src={item.product_image || 'https://images.unsplash.com/photo-1441986300917-64674bd600d8?w=200'}
                    alt={item.product_name}
                    className="w-full h-full object-cover"
                  />
                </div>
                <div className="flex-1 min-w-0">
                  <div className="text-sm font-medium text-gray-900 truncate">
                    {item.product_name}
                  </div>
                  <div className="text-xs text-gray-500">
                    {item.size && `${item.size} `}
                    {item.color && `${item.color} `}
                    × {item.quantity}
                  </div>
                  <div className="text-sm font-medium text-pink-600">
                    ¥{(item.price * item.quantity).toFixed(2)}
                  </div>
                </div>
              </div>
            ))}
            
            {order.order_items && order.order_items.length > 3 && (
              <div className="text-sm text-gray-500 text-center">
                还有 {order.order_items.length - 3} 件商品...
              </div>
            )}
          </div>

          {/* Order Summary */}
          <div className="border-t pt-4">
            <div className="flex items-center justify-between mb-2">
              <span className="text-sm text-gray-600">
                共 {order.order_items?.reduce((sum, item) => sum + item.quantity, 0)} 件商品
              </span>
              <span className="text-lg font-bold text-pink-600">
                ¥{order.total_amount.toFixed(2)}
              </span>
            </div>
            
            <div className="flex gap-2">
              <Button asChild variant="outline" size="sm" className="flex-1">
                <Link to={`/orders/${order.id}`}>
                  <Eye className="h-4 w-4 mr-2" />
                  查看详情
                </Link>
              </Button>
              
              {order.status === 'pending' && (
                <Button size="sm" className="flex-1 bg-pink-600 hover:bg-pink-700">
                  立即付款
                </Button>
              )}
              
              {order.status === 'shipped' && (
                <Button size="sm" className="flex-1">
                  确认收货
                </Button>
              )}
              
              {order.status === 'delivered' && (
                <Button variant="outline" size="sm" className="flex-1">
                  评价商品
                </Button>
              )}
            </div>
          </div>
        </CardContent>
      </Card>
    );
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-pink-600"></div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-4">我的订单</h1>
          <p className="text-gray-600">查看和管理您的所有订单</p>
        </div>

        {/* Order Tabs */}
        <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
          <TabsList className="grid w-full grid-cols-6">
            <TabsTrigger value="all">全部</TabsTrigger>
            <TabsTrigger value="pending">待付款</TabsTrigger>
            <TabsTrigger value="paid">已付款</TabsTrigger>
            <TabsTrigger value="shipped">已发货</TabsTrigger>
            <TabsTrigger value="delivered">已完成</TabsTrigger>
            <TabsTrigger value="cancelled">已取消</TabsTrigger>
          </TabsList>

          <TabsContent value="all" className="space-y-6">
            {getFilteredOrders().length === 0 ? (
              <div className="text-center py-16">
                <ShoppingBag className="h-24 w-24 text-gray-300 mx-auto mb-6" />
                <h2 className="text-2xl font-semibold text-gray-900 mb-4">暂无订单</h2>
                <p className="text-gray-600 mb-8">您还没有任何订单，快去购买心仪的商品吧！</p>
                <Button asChild size="lg">
                  <Link to="/products">
                    <Package className="h-5 w-5 mr-2" />
                    去购物
                  </Link>
                </Button>
              </div>
            ) : (
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {getFilteredOrders().map((order) => (
                  <OrderCard key={order.id} order={order} />
                ))}
              </div>
            )}
          </TabsContent>

          <TabsContent value="pending" className="space-y-6">
            {getFilteredOrders('pending').length === 0 ? (
              <div className="text-center py-16">
                <Clock className="h-24 w-24 text-gray-300 mx-auto mb-6" />
                <h2 className="text-2xl font-semibold text-gray-900 mb-4">暂无待付款订单</h2>
                <p className="text-gray-600">您没有需要付款的订单</p>
              </div>
            ) : (
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {getFilteredOrders('pending').map((order) => (
                  <OrderCard key={order.id} order={order} />
                ))}
              </div>
            )}
          </TabsContent>

          <TabsContent value="paid" className="space-y-6">
            {getFilteredOrders('paid').length === 0 ? (
              <div className="text-center py-16">
                <Package className="h-24 w-24 text-gray-300 mx-auto mb-6" />
                <h2 className="text-2xl font-semibold text-gray-900 mb-4">暂无已付款订单</h2>
                <p className="text-gray-600">您没有已付款的订单</p>
              </div>
            ) : (
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {getFilteredOrders('paid').map((order) => (
                  <OrderCard key={order.id} order={order} />
                ))}
              </div>
            )}
          </TabsContent>

          <TabsContent value="shipped" className="space-y-6">
            {getFilteredOrders('shipped').length === 0 ? (
              <div className="text-center py-16">
                <Truck className="h-24 w-24 text-gray-300 mx-auto mb-6" />
                <h2 className="text-2xl font-semibold text-gray-900 mb-4">暂无已发货订单</h2>
                <p className="text-gray-600">您没有已发货的订单</p>
              </div>
            ) : (
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {getFilteredOrders('shipped').map((order) => (
                  <OrderCard key={order.id} order={order} />
                ))}
              </div>
            )}
          </TabsContent>

          <TabsContent value="delivered" className="space-y-6">
            {getFilteredOrders('delivered').length === 0 ? (
              <div className="text-center py-16">
                <CheckCircle className="h-24 w-24 text-gray-300 mx-auto mb-6" />
                <h2 className="text-2xl font-semibold text-gray-900 mb-4">暂无已完成订单</h2>
                <p className="text-gray-600">您没有已完成的订单</p>
              </div>
            ) : (
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {getFilteredOrders('delivered').map((order) => (
                  <OrderCard key={order.id} order={order} />
                ))}
              </div>
            )}
          </TabsContent>

          <TabsContent value="cancelled" className="space-y-6">
            {getFilteredOrders('cancelled').length === 0 ? (
              <div className="text-center py-16">
                <XCircle className="h-24 w-24 text-gray-300 mx-auto mb-6" />
                <h2 className="text-2xl font-semibold text-gray-900 mb-4">暂无已取消订单</h2>
                <p className="text-gray-600">您没有已取消的订单</p>
              </div>
            ) : (
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {getFilteredOrders('cancelled').map((order) => (
                  <OrderCard key={order.id} order={order} />
                ))}
              </div>
            )}
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
};

export default Orders;